/**
 * Created by chenxq on 2017/12/11.
 */
import React,{PureComponent} from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Table, Card, Button, Alert ,Popconfirm,Modal, Row, message,Divider} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import {listParams} from '../defaultData';
import {findObjByKey,convertLongToString} from '../../utils/index';
import Info from '../../components/ClientDetail/Info';
import CheckList from '../../utils/CheckList';
import styles from './index.less';
@connect(state => ({
  user:state.usermanagement,
  roleList:[],
  group:state.group
}))
export default class extends PureComponent{
  state={
    loading:false,
    list:[],
    pagination:{
      ...listParams
    },
    editObj:{},
    isvisible:false

  }
  defaultUser={
    userName: "",
    roleId: "",
    phone: "",
    gender: "2",
    login: "",
    password: "",
  }
  columns = [{
    title: '用户姓名',
    dataIndex: 'userName',
    //render: text => <a href="#">{text}</a>,
  }, {
    title: "登录账号",
    dataIndex: "login"
  }, {
    title: "用户角色",
    dataIndex: "roleId",
    render:(roleId)=>{
      let {roleList} = this.props.user;
      if(!roleId || !(roleList && roleList.length) ){
        return "";
      }
      //console.log(roleId);
      let obj = findObjByKey(roleList,roleId,"id");
      return obj ? obj.roleName : "未知"
    }
  }, {
    title:"用户组",
    dataIndex:"groupName",
  },{
    title: "联系电话",
    dataIndex: "phone"
  }, {
    title: "创建时间 ",
    dataIndex: "createTime",
    render:(datetime)=>{
      return datetime ? convertLongToString(datetime) : ""
    }
  }, /*{
   title: "最后登录时间",
   dataIndex: "lastLoginTime",
   render:(datetime)=>{
   return datetime ? convertLongToString(datetime) : ""
   }
   },*/ {
    title: "操作",
    dataIndex: "id",
    render: (id,record) =>
      <div className={styles.operations}>
        <a onClick={this.showDetail.bind(this, id,record)}>编辑</a>
        <Divider type="vertical" />
        <Popconfirm title="确认要删除该用户?" onConfirm={this.remove.bind(this,id)}><a>删除</a></Popconfirm>
      </div>
  }];
  // 编辑
  showDetail(id,record){
    this.setState({
      editObj:{...record,
        password:""
      },
      isvisible:true
    })
  }

  tableChange = (pagination, filters, sorter) => {
    this.getList(pagination);
  };
  getList=(page={current:1})=>{
    let {dispatch} = this.props;
    let pagination = Object.assign({},this.state.pagination,page);
    this.setState({
      pagination
    },()=>{
      dispatch({
        type: 'usermanagement/fetchList',
        payload: pagination,
      })
    })
  }
  componentDidMount(){
    this.getList();
    // 获取分组列表
    this.props.dispatch({
      type:'group/fetchList',
      payload:{}
    })
    //获取角色列表
    this.props.dispatch({
      type:'usermanagement/fetchRoleList',
      payload:{}
    })
  }
  checkAll = (data,isAdd)=>{
    if(!data.userName){
      message.warn("请输入用户姓名");
      return false;
    }
    if(!data.login || !CheckList.username(data.login)){
      message.warn("请输入正确的登录账号(只能是英文或数字)");
      return false;
    }
    if(isAdd){
      if(!data.password){
        message.warn("请输入密码");
        return false;
      }

    }

    if(data.password && !CheckList.password(data.password)){
      message.warn("请输入6-20位密码");
      return false;
    }
    return true;

  };
  // 删除
  remove(id){
    let _this=this;
    this.props.dispatch({
      type:'usermanagement/fetchRemove',
      payload:[id]
    }).then(jsonData=>{
      if(jsonData.result){
        message.success("删除成功",0.8,()=>{
          _this.getList();
        })
      }else{
        message.error(jsonData.msg);
      }
    })
  }
  editUser=()=>{
    let {dispatch,currentUser,user,group} = this.props;
    let _this = this;
    let editObj = this.state.editObj;
    if(!this.checkAll(editObj,false)){
      return false;
    }
    let formData = Object.assign({}, editObj);
    let {roleList=[]} =user;
    let {groupList=[]} =group;
    //同时，组ID需要赋值成第一个
    let gList = this.formatGroupList(groupList);
    !formData.groupId && (formData.groupId = gList[0].key);
    //如果用户不修改密码的话，密码字段不需要给后端
    if(!formData.password){
      delete formData.password;
    }
    dispatch({
      type:'usermanagement/fetchEdit',
      payload:formData
    }).then(jsonData=>{
      if(jsonData.result){
        message.success("修改成功",0.8,()=>{
          _this.handleCancel();
          _this.getList(_this.state.pagination);
        })
      }else{
        message.error(jsonData.msg);
      }
    })
  }
  addUser=()=>{
    let {dispatch,user,group} = this.props;
    let _this = this;
    let editObj = this.state.editObj;
    let formData = Object.assign({}, editObj);
    let {roleList=[]} =user;
    let {groupList=[]} =group;
    //新增时没有选择过的话roleId为空
    if(!editObj.roleId){
      let fRoleList = this.formatRoleList(roleList);
      formData.roleId = fRoleList[0].key;
    }
    //同时，组ID需要赋值成第一个
    let gList = this.formatGroupList(groupList);
    !formData.groupId && (formData.groupId = gList[0].key);
    //不需要显示用户分组信息的时候，不需要groupId的值
    if(this.shouldShowGroup(formData.roleId)==1){
      delete formData.groupId;
    }
    if(!this.checkAll(formData,true)){
      return false;
    }
    dispatch({
      type:'usermanagement/fetchAdd',
      payload:formData
    }).then(jsonData=>{
      if(jsonData.result){
        message.success("添加成功",0.8,()=>{
          _this.handleCancel();
          _this.getList();
        })
      }else{
        message.error(jsonData.msg);
      }
    })


  }
  handleCancel=()=>{
    this.setState({
      isvisible:false
    })
  }
  setKeyValue=(key,value)=>{
    let obj=Object.assign({},this.state.editObj);
    obj[key]=value;
    this.setState({
      editObj: obj
    })
  }

  //是否应该显示分组信息，目前是如果roleId在不需要分组信息里边就不显示
  shouldShowGroup = (roleId)=>{
    let {user} = this.props;
    let {roleList=[]} =user;
    let roleObj=roleList.find(item=>item.id===roleId);
    if(roleObj && (roleObj.code=='SuperAdmin')){
      return 1;
    }
    if(roleObj && (roleObj.code=='FrontDeskDirector' || roleObj.code=='BackstageDirector')){
      return 2;
    }
    return 3;
  };
  formatRoleList = (list)=>{
    let format = list.map((v)=>{
      return({
        key:v.id,
        name:v.roleName,
      })
    });
    return format || [];
  };
  formatGroupList = (list)=>{
    let format = list.map((v)=>{
      return({
        key:v.id,
        name:v.name,
      })
    });
    return format || [];
  };
  render(){
    let {user,group} = this.props;
    let state= this.state;
    let {editObj={}}= state;
    let {roleList=[]} =user;
    let {groupList=[]} =group;
    roleList=this.formatRoleList(roleList);
    groupList=this.formatGroupList(groupList);
    let showGroup = this.shouldShowGroup(editObj.roleId);
    return (<PageHeaderLayout title="用户管理">
      <Card bordered={false}>
        <div className={styles.tableListOperator}>
          <Button icon="plus" type="primary" onClick={this.showDetail.bind(this,null,Object.assign({},this.defaultUser))}>
            新增用户
          </Button>
        </div>
        <div style={{marginTop: 20}}>
          <Table rowKey="id"
                 loading={user.loading}
                 columns={this.columns}
                 dataSource={user.userList}
                 pagination={{...this.state.pagination,total:user.userTotal}}
                 onChange={this.tableChange}
          />
        </div>
      </Card>
      <Modal title={editObj.id ? "编辑用户":"新建用户"}
             onOk={editObj.id? this.editUser : this.addUser}
             onCancel={this.handleCancel}
             visible={state.isvisible}>
        <div className={styles.addClient}>
          <form>
            <Row type="flex" align="middle">
              <Info label="用户姓名"
                    required
                    value={editObj.userName}
                    id="userName"
                    placeholder="请输入用户姓名"
                    onChange={this.setKeyValue.bind(this, "userName")}/>
            </Row>
            <Row type="flex" align="middle">
              <Info label="分机号"
                    value={editObj.agentId}
                    id="agentId"
                    onChange={this.setKeyValue.bind(this, "agentId")}/>
            </Row>
            <Row type="flex" align="middle">
              {roleList && roleList.length && <Info label="角色"
                                                    type="select"
                                                    value={editObj.roleId || roleList[0].key}
                                                    required
                                                    data={roleList}
                                                    onChange={this.setKeyValue.bind(this, "roleId")}/>
              }

            </Row>
            {groupList && groupList.length && showGroup!=1 && <Row type="flex" align="middle">
              {showGroup==3 && <Info label="分组"
                                      type="select"
                                      value={editObj.groupId}
                                      data={groupList}
                                      required
                                      onChange={this.setKeyValue.bind(this, "groupId")}/>}
              { showGroup==2 && <Info label="分组"
                                      type="select"
                                      value={editObj.groupIds || []}
                                      data={groupList}
                                      required
                                      mode="multiple"
                                      onChange={this.setKeyValue.bind(this, "groupIds")}
              />}
            </Row>}
            <Row type="flex" align="middle">
              <Info label="联系电话"
                    value={editObj.phone}
                    onChange={this.setKeyValue.bind(this, "phone")}/>
              <Info label="性别"
                    type="select"
                    value={editObj.gender == 0 ? 0 : (editObj.gender*1 || 2 )}
                    data={[{
                      key: 0, name: "男"
                    }, {
                      key: 1, name: "女"
                    },{
                      key: 2,name: "未知"
                    }]} onChange={this.setKeyValue.bind(this, "gender")}/>
            </Row>
            <Row type="flex" align="middle">
              <Info label="登录账号"
                    required
                    value={editObj.login}
                    disabled={editObj.id?true:false}
                    placeholder="支持英文和数字的组合"
                    onChange={this.setKeyValue.bind(this, "login")}/>
            </Row>
            <Row type="flex" align="middle">
              <Info label="登录密码"
                    required
                    value={editObj.password}
                    placeholder={editObj.id ?"不需要修改请留空":"请输入密码(6-20个字符)"}
                    type="password"
                    onChange={this.setKeyValue.bind(this, "password")}/>
            </Row>
          </form>
        </div>

      </Modal>

    </PageHeaderLayout>)
  }
}
